using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;


using System.ServiceModel;
using System.Security.Cryptography.X509Certificates;

using eBookDomain.AWSE;
using eBook.Services.Amazon;
using eBook.Core.BusinessObjects;
using eBook.Services.AWSE;

namespace eBook.Domain
{
  public enum SearchIndex
  {
    Apparel, Automotive, Baby, Beauty, Blended, Books,
    Classical, DigitalMusic, DVD, Electronics, GourmetFood,
    HealthPersonalCare, Jewelry, Kitchen, Magazines, Merchants,
    Miscellaneous, Music, MusicalInstruments, MusicTracks,
    OfficeProducts, OutdoorLiving, PCHardware, PetSupplies,
    Photo, Restaurants, Software, SportingGoods, Tools, Toys,
    VHS, Video, VideoGames, Wireless, WirelessAccessories
  }   

  public class AWSSearchEngine
  {

#region Properties 

    private int _itemPage;
    public int ItemPage
    {
        get { return _itemPage; }
        set { _itemPage = value; }
    }

    private SearchCriteria _criteria;
    public SearchCriteria Criteria
    {
        get { return _criteria; }
        set { _criteria = value; }
    }

    private String _subscriptionId;
    public String SubscriptionId
    {
        get { return _subscriptionId; }
        set { _subscriptionId = value; }
    }

    private String[] _responseGroup;
    public String[] ResponseGroup
    {
        get { return _responseGroup; }
        set { _responseGroup = value; }
    }

    //private String _power;
    //public String Power
    //{
    //    get { return _power; }
    //    set { _power = value; }
    //}

    private SearchIndex _searchIndex;
    public SearchIndex SearchIndex
    {
        get { return _searchIndex; }
        set { _searchIndex = value; }
    }

    private ItemSearchRequest _request;
    public ItemSearchRequest Request
    {
        get { return _request; }
        set { _request = value; }
    }

    private ItemSearch _itemSearch;
    public ItemSearch ItemSearch
    {
      get { return _itemSearch; }
      set { _itemSearch = value; }
    }

    private AWSECommerceServicePortTypeClient _client;
    public AWSECommerceServicePortTypeClient Client
    {
      get { return _client; }
        //set { _service = value; }
    }

    private List<boBookInfo> _books;
    public List<boBookInfo> Books
    {
        get { return _books; }
        set { _books = value; }
    }        
        
#endregion

    private const string accessKeyId = "1REKPA0HEES4TPN9ZE02";
    private const string secretKey = "4pI0a2ZyLXdGI8bOMj7aD/04I2ao9FAF8jpZYMao";
    private const string subscriptionId = "1WRF74XYWAF1YEEE1YG2";

    public AWSSearchEngine()
    {
      BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
      binding.Name = "AWSECommerceServiceBinding";
      binding.MaxReceivedMessageSize = int.MaxValue;

      _client = new AWSECommerceServicePortTypeClient(
              binding,
              new EndpointAddress("https://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));

      _client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(accessKeyId, secretKey));
      _itemSearch = new ItemSearch();
      _itemSearch.AWSAccessKeyId = accessKeyId;

      _request = new ItemSearchRequest();
      _books = new List<boBookInfo>();
      _criteria = new SearchCriteria();
      _itemPage = 1;
      
      
     

      this.SearchIndex = SearchIndex.Books;
      
      // Author, BrowseNode, Condition, ItemPage, Keywords, MaximumPrice,MerchantId,MinimumPrice,PowerPublisher
      // Sort,State,TextStream,Title
            
      this.ResponseGroup = new string[] { "ItemAttributes", "Images", "EditorialReview" };      
            
    }

    public void Search()
    {
      this.Search(1);
    }
    
    public void NextPage()
    {
      Search(++_itemPage);
    }
        
    public void Search(int pageNo)
    {           
      _request.SearchIndex = _searchIndex.ToString();
      _request.ResponseGroup = _responseGroup;

      _request.Power = _criteria.PowerSearchText;

      

      _request.Author = _criteria.Author;
      _request.Title = _criteria.Title;
      _request.Keywords = _criteria.Keywords;

      _request.ItemPage = pageNo.ToString();
      
      _itemPage = pageNo;

      _itemSearch.Request = new ItemSearchRequest[] { _request };
      
      //_itemSearch.SubscriptionId = _subscriptionId;
      






      ItemSearchResponse response = _client.ItemSearch(_itemSearch);
      
      if (response == null)
        throw new Exception("Server Error - no response recieved!");

      Items[] responseItemsArray = response.Items;
      
      // Check for errors, stop at first error
      if (responseItemsArray == null)
        throw new Exception("Server Error - empty response!"); 

      if (responseItemsArray[0].Request.Errors != null)
        throw new Exception(responseItemsArray[0].Request.Errors[0].Message);           

      _books.Clear();

      // go through received response     
      foreach (Items items in responseItemsArray)
      {        
        if (items != null)
        {
          if (items.Item != null)
            foreach (Item item in items.Item)
              if (item != null)
                _books.Add(CreateBook(item));                          
        }        
      }
      return;
    }



    // examine properties of the item and build up a book   
    private boBookInfo CreateBook(Item item)    
    {
      boBookInfo b = new boBookInfo();
      StringBuilder reviewBuilder = new StringBuilder();
      
      b.ASIN          = item.ASIN;
      b.DetailPageURL = item.DetailPageURL;

      b.SmallImageURL  = item.SmallImage == null  ? string.Empty : item.SmallImage.URL ;
      b.MediumImageURL = item.MediumImage == null ? string.Empty : item.MediumImage.URL;
      b.LargeImageURL  = item.LargeImage == null  ? string.Empty : item.LargeImage.URL;
      
      if ( item.EditorialReviews != null )
      {
        foreach ( EditorialReview review in item.EditorialReviews )
          reviewBuilder.Append(string.Format( "{0} <b>{1}</b><br>{2}"
                                            , string.IsNullOrEmpty(b.EditorialReview) ? string.Empty : "<p>"
                                            , review.Source
                                            , review.Content));  
        b.EditorialReview = reviewBuilder.ToString();
      }
        
      ItemAttributes itemAttributes = item.ItemAttributes;
      if (itemAttributes != null)
      {
        b.AudienceRating = itemAttributes.AudienceRating;
        b.Authors = itemAttributes.Author;
        b.Binding = itemAttributes.Binding;
        b.DeweyDecimalNumber = itemAttributes.DeweyDecimalNumber;
        b.ISBN10 = itemAttributes.ISBN;
        b.NumberOfPages = itemAttributes.NumberOfPages ;
        b.PublicationDate = itemAttributes.PublicationDate;
        b.Publisher = itemAttributes.Publisher;
        b.Title = itemAttributes.Title;
        
        if (itemAttributes.ItemDimensions != null)                 
          b.ItemDimensions = string.Format( "{0} {1}"
                                          , itemAttributes.ItemDimensions.Height
                                          , itemAttributes.ItemDimensions.Width);
        
        b.ReadingLevel = itemAttributes.ReadingLevel;
        if (itemAttributes.ListPrice != null) 
          b.ListPrice = itemAttributes.ListPrice.Amount;
        
        b.Edition = itemAttributes.Edition;
      };    

      return b;
    }
    
    
    
    
    

  }
}

